package com.zxcl.controller;

import com.zxcl.domain.SysMenu;
import com.zxcl.ex.BusinessException;
import com.zxcl.model.Result;
import com.zxcl.service.SysMenuService;
import com.zxcl.utils.AuthUtil;
import com.zxcl.vo.MenuPermsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/sys/menu")
@Api(tags = "菜单管理相关接口")
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;


    @GetMapping("nav")
    @ApiOperation("加载菜单")
    public Result<MenuPermsVO> loadMenuAndPerms(){
        MenuPermsVO menuPermsVO=new MenuPermsVO();
        //得到权限
        Set<String> perms = AuthUtil.getPerms();
        //设置进去
        menuPermsVO.setAuthorities(perms);
        //根据用户ID查询用户的菜单
        Long userId = AuthUtil.getUserId();
        List<SysMenu> sysMenuList=sysMenuService.findUserMenus(userId);
        menuPermsVO.setMenuList(sysMenuList);
        return Result.success(menuPermsVO);
    }

    @GetMapping("table")
    @ApiOperation("加载当前用户的菜单")
    public Result<List<SysMenu>> loadSysMenuPage() {
        List<SysMenu> sysMenuPage = sysMenuService.list();
        return Result.success(sysMenuPage);
    }


    @GetMapping("list")
    @ApiOperation("加载菜单")
    public Result<List<SysMenu>> loadSysMenuList() {
        List<SysMenu> sysMenus = sysMenuService.loadSysMenuList();
        return Result.success(sysMenus);
    }

    @GetMapping("info/{userId}")
    @ApiOperation("查询当前菜单的信息")
    public Result<SysMenu> loadMenu(@PathVariable Long userId) {
        SysMenu menu = sysMenuService.getById(userId);
        return Result.success(menu);
    }

    @PostMapping
    @ApiOperation("添加菜单的信息")
    public Result<String> addSysMenu(@RequestBody SysMenu sysMenu){
        boolean flag = sysMenuService.save(sysMenu);
        return Result.handle(flag);
    }

    @DeleteMapping("{userId}")
    @ApiOperation("删除菜单的信息")
    public Result<String> removeUser(@PathVariable Long userId){
        boolean row = sysMenuService.removeById(userId);
        return Result.handle(row);
    }
}
